package com.aruba.diff;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.aruba.diff.DiffUtils.NEW_FILE_PATH;
import static com.aruba.diff.DiffUtils.NEW_FILE_PATH_BY_PATCH;
import static com.aruba.diff.DiffUtils.OLD_FILE_PATH;
import static com.aruba.diff.DiffUtils.PATCH_FILE_PATH;

public class MainActivity extends AppCompatActivity {
    private static  final String tag = MainActivity.class.getSimpleName();
    private boolean isPatching;
    private boolean isDiffing;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
    private Thread diffThread;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        diffThread = new Thread(){
            @Override
            public void run() {
                Log.i(tag,"diff startTime:"+simpleDateFormat.format(new Date()));
                int ret = DiffUtils.diff(OLD_FILE_PATH, NEW_FILE_PATH, PATCH_FILE_PATH);
                if (ret == 0) {
                    isDiffing = false;
                }
                Log.i(tag,"diff endTime:"+simpleDateFormat.format(new Date()));
            }
        };
        // Example of a call to a native method
        findViewById(R.id.sample_text).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isDiffing || isPatching) {
                    return;
                }

                Toast.makeText(MainActivity.this, "start diff", Toast.LENGTH_SHORT).show();
                isDiffing = true;
                diffThread.start();
            }
        });

        findViewById(R.id.tv_patch).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPatching || isDiffing) {
                    return;
                }

                Toast.makeText(MainActivity.this, "start patch", Toast.LENGTH_SHORT).show();
                isPatching = true;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(tag,"patch startTime:"+simpleDateFormat.format(new Date()));
                        int ret = DiffUtils.patch(OLD_FILE_PATH, NEW_FILE_PATH_BY_PATCH, PATCH_FILE_PATH);
                        if (ret == 0) {
                            isPatching = false;
                        }
                        Log.i(tag,"patch endTime:"+simpleDateFormat.format(new Date()));
                    }
                }).start();
            }
        });
    }

}
